from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import Dict, Any

mcp = FastMCP("Scipy MCP Server")

"""
Scipy MCP Server

面向软件：scipy (Scientific Computing Library for Python)

MCP tools 列表：
1. scipy_run_test
   - 用途：运行 scipy 功能测试，验证 scipy 库的基本功能
   - 参数：无
   - 返回结构：统一的命令行执行结果 JSON
"""

@mcp.tool()
def scipy_run_test() -> Dict[str, Any]:
    """
    运行 scipy 功能测试
    
    用途：执行 scipy 功能测试脚本，验证 scipy 库的安装和基本功能是否正常
    参数：无
    返回 JSON 结构：
    {
        "success": bool,      # 命令是否成功执行
        "command": str,       # 执行的完整命令
        "exit_code": int,     # 命令退出码
        "stdout": str,        # 标准输出内容
        "stderr": str         # 标准错误内容
    }
    """
    command = ["python3", "test_python3-scipy.py"]
    
    try:
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out after 30 seconds"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Command execution failed: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()